<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="purchaseOrderNo">
        <el-input v-model="queryParams.purchaseOrderNo" placeholder="请输入采购订单编号" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入供应商" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="采购员" prop="orderUserName">
        <el-input v-model="queryParams.orderUserName" placeholder="请输入采购员" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="审核人" prop="eorderUserName">
        <el-input v-model="queryParams.eorderUserName" placeholder="请输入审核人" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="申请编号" prop="purchaseApplyNo">
        <el-input v-model="queryParams.purchaseApplyNo" placeholder="请输入采购申请" clearable @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 198px">
          <el-option v-for="dict in purchase_order_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" v-hasPermi="['purchase:order:add']" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['purchase:order:add']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" v-hasPermi="['purchase:order:list']"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
<!--      <el-table-column label="订单编号" align="center" prop="purchaseOrderNo" width="210"/>-->
      <el-table-column label="订单编号" align="center" prop="purchaseOrderNo" width="210">
        <template #default="scope">
          <span @click="handleShowDetails(scope.row)" style="color: #1c84c6">{{scope.row.purchaseOrderNo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" prop="purchaseApplyNo" width="210">
        <template #default="scope">
          <router-link to="/purchase/apply" style="color: #1c84c6">{{scope.row.purchaseApplyNo}}</router-link>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="供应商电话" align="center" prop="supplierTel" width="120"/>
      <el-table-column label=申请人 align="center" prop="applyUserName" />
      <el-table-column label=申请部门 align="center" prop="deptName" />
      <el-table-column label="采购员" align="center" prop="orderUserName" />
      <el-table-column label="订单金额" align="center" prop="orderPrice" />
      <el-table-column label="审核人" align="center" prop="eorderUserName" />
      <el-table-column label="预计交单日期" align="center" prop="planOrderDate" width="120">
        <template #default="scope">
          <span>{{ scope.row.planOrderDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际交单时间" align="center" prop="orderDate" width="120">
        <template #default="scope">
          <span>{{ scope.row.orderDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="purchase_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
        <template #default="scope">
          <!-- 根据 status 值显示不同按钮 -->
          <template v-if="scope.row.status === 0">
            <el-button v-if="isPurchaser(scope.row)" link type="primary" icon="Edit" v-hasPermi="['purchase:order:edit']" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-if="isPurchaser(scope.row)" link type="primary" icon="Delete" v-hasPermi="['purchase:order:edit']" @click="handleDelete(scope.row)">删除</el-button>
            <el-button v-if="isPurchaser(scope.row)" link type="primary" icon="link" v-hasPermi="['purchase:order:edit']" @click="handleSubmit(scope.row)">提交</el-button>
          </template>
          <template v-else-if="scope.row.status === 1">
            <el-button v-if="isApprove(scope.row)" link type="primary" icon="CircleCheck" v-hasPermi="['purchase:order:edit']" @click="handleApprove(scope.row)" >申请通过</el-button>
            <el-button v-if="isApprove(scope.row)" link type="primary" icon="CircleClose" v-hasPermi="['purchase:order:edit']" @click="handleReject(scope.row)" >审核驳回</el-button>
          </template>
<!--          <template v-else-if="scope.row.status === 2">-->
<!--            <el-button v-if="isPurchaser(scope.row)" link type="primary" icon="CircleCheck" @click="handleApprove(scope.row)" >已到货</el-button>-->
<!--          </template>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" v-model="open" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" >
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="订单编号" prop="purchaseOrderNo">
            <el-input v-model="form.purchaseOrderNo" placeholder="请输入采购订单编号" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 180px">
              <el-option v-for="option in selectSupplierOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="采购员" prop="orderUserId">
            <el-input v-model="form.orderUserName" placeholder="请输入采购员" disabled />
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="申请编号" prop="purchaseApplyId">
            <el-select v-model="form.purchaseApplyId" placeholder="请选择申请编号" style="width: 240px">
              <el-option v-for="option in selectApplyOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="审核人" prop="eorderUserId">
            <el-select v-model="form.eorderUserId" placeholder="请选择审核人" style="width: 140px">
              <el-option v-for="option in selectUserOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预计交单日期" prop="planOrderDate">
            <el-date-picker clearable v-model="form.planOrderDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择预计交单日期"></el-date-picker>
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="订单金额" prop="orderPrice" >
            <el-input v-model="form.orderPrice" placeholder="订单金额" disabled />
          </el-form-item>
        </div>
        <div>
          <h2>采购订单清单</h2>
          <el-col :span="1.5" class="mb8">
            <el-button type="primary" plain icon="Plus" @click="handleAddMaterial">新增</el-button>
          </el-col>

          <el-table  style="height: 220px; overflow: auto;" :data="purchaseOrderMaterials">
            <el-table-column label="物料名称" align="center" prop="materialName" >
              <template #default="scope">
                <el-select v-model="scope.row.materialId" placeholder="Select" size="large" style="width: 240px">
                  <el-option v-for="option in selectMaterialOptions" :key="option.value" :label="option.label" :value="option.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="purchaseOrderNumber" >
              <template #default="scope">
                <el-input-number min="0" v-model="scope.row.purchaseOrderNumber"  @change="handleChange(scope.row)"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column v-if="!data.isAdding" label="操作" align="center" class-name="small-padding fixed-width" width="300">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="handleDeleteMaterial(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!--  采购订单详情页  -->
    <el-dialog :title="title" v-model="openA" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" >
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="订单编号" >
            <el-input v-model="form.purchaseOrderNo" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="供应商" >
            <el-input v-model="form.supplierName" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="采购员">
            <el-input v-model="form.orderUserName" placeholder="请输入采购员" disabled />
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="申请编号">
            <el-input v-model="form.purchaseApplyNo" placeholder="请输入采购员" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="审核人">
            <el-select v-model="form.eorderUserId" placeholder="请选择审核人" style="width: 140px" disabled>
              <el-option v-for="option in selectUserOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预计交单日期" prop="planOrderDate">
            <el-date-picker clearable v-model="form.planOrderDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择预计交单日期" disabled></el-date-picker>
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: space-between;">
          <el-form-item label="实际交单时间" prop="orderDate">
            <el-date-picker disabled clearable v-model="form.orderDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择实际交单时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="订单金额" prop="orderPrice" >
            <el-input disabled v-model="form.orderPrice"   placeholder="订单金额" />
          </el-form-item>
        </div>
        <div>
          <h2>采购订单清单</h2>
          <el-table  style="height: 220px; overflow: auto;" :data="purchaseOrderMaterials">
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="数量" align="center" prop="purchaseOrderNumber" />
            <el-table-column label="单位" align="center" prop="unitId">
              <template #default="scope">
                <dict-tag :options="unit_type" :value="scope.row.unitId" />
              </template>
            </el-table-column>
            <el-table-column label="单价" align="center" prop="materialPrice" />
            <el-table-column label="总价" align="center">
              <template #default="scope">
                <span>{{ scope.row.totalPrice }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder,getCGDD,changeOrderStatus,delMaterial } from "@/api/purchase/order";
import { addPayable} from "@/api/finance/payable"
import useUserStore from "../../../store/modules/user.js";
import {listMaterials} from "../../../api/base/materials.js";
import {listUser} from "../../../api/system/user.js";
import {ElMessageBox} from "element-plus";
import {changeStatus, listPurchaseApply} from "../../../api/purchase/apply/apply.js";
import {listSupplier} from "../../../api/base/supplier.js";

const { proxy } = getCurrentInstance();
const { purchase_order_status ,unit_type} = proxy.useDict('purchase_order_status','unit_type');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openA = ref(false);

const data = reactive({
  form: {
    purchaseOrderMaterials: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    purchaseOrderNo: null,
    supplierId: null,
    orderUserId: null,
    eorderUserId: null,
    purchaseApplyId: null,
    planOrderDate: null,
    orderDate: null,
    status: null,
    orderUserName: null,
    supplierName: null,
    purchaseApplyNo: null,
    orderPrice: null,
    purchasePrice: null
  },
  rules: {
    supplierId: [
      { required: true, message: "供应商不能为空", trigger: "blur" }
    ],
    eorderUserId: [
      { required: true, message: "审核人不能为空", trigger: "blur" }
    ],
    purchaseApplyId: [
      { required: true, message: "审核人不能为空", trigger: "blur" }
    ]
  }
});

//采购订单清单列表
const purchaseOrderMaterials = ref([])

const { queryParams, form, rules } = toRefs(data);

/** 查询采购订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    purchaseOrderNo: null,
    supplierId: null,
    orderUserId: null,
    eorderUserIdt: null,
    purchaseApplyId: null,
    planOrderDate: null,
    orderDate: null,
    orderPrice:null,
    status: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 获取登录对象并获取其 id 值
let userId = useUserStore().id;
let userName = useUserStore().name;
/** 新增按钮操作 */
function handleAdd() {
  reset();
  purchaseOrderMaterials.value = []
  form.value.purchaseOrderMaterials = purchaseOrderMaterials;
  data.isAdding = true;
  form.value.orderUserId = userId;
  form.value.orderUserName = userName;
  getCGDD().then(response => {
    form.value.purchaseOrderNo= response.msg
    // 初始化订单金额为 0
    form.value.orderPrice = 0;
  })
  open.value = true;
  title.value = "添加采购订单";
}
// 新增：用于存储用户列表的ref
const userList = ref([]);
const materialsList = ref([]);
const applyList = ref([]);
const supplierList = ref([])
// 获取用户列表的函数
const getUsers = async () => {
  const response = await listUser();
  userList.value = response.rows;
  // console.log(userList.value)
};
/** 查询物料管理列表 */
const getMaterialList = async () =>  {
  const response = await listMaterials();
  materialsList.value = response.rows
  // console.log(materialsList.value)
}
// 获取采购申请单列表
const getApplyList = async () => {
  const response = await listPurchaseApply();
  applyList.value = response.rows;
  console.log(applyList.value)
};
// 获取供应商列表
async function getSupplier() {
  const response = await listSupplier();
  supplierList.value = response.rows
  // console.log(supplierList.value)
}

// 在页面加载时获取用户列表、物料列表
onMounted(() => {
  getUsers();
  getMaterialList();
  getApplyList();
  getSupplier();
});
// 新增：计算属性，生成el - select选项
const selectUserOptions = computed(() => {
  return userList.value.map(user => ({ label: user.userName, value: user.userId }));
});
const selectMaterialOptions = computed(() => {
  return materialsList.value.map(material => ({ label: material.materialName, value: material.id, price:material.price}));
});
const selectApplyOptions = computed(() => {
  return applyList.value.map(purchaseApply => ({ label: purchaseApply.purchaseApplyNo, value: purchaseApply.id }));
});
const selectSupplierOptions = computed(() => {
  return supplierList.value.map(supplier => ({ label: supplier.companyName, value: supplier.id }));
});
//新增采购订单清单
function handleAddMaterial(){
  let obj = {
    materialId: '',
    purchaseOrderNumber: '',
  }
  purchaseOrderMaterials.value.push(obj);
  // 每次新增物料后重新计算订单金额
  TotalOrderPrice();
}
function handleChange(row) {
  console.log(row);
  // 当数量改变时重新计算订单金额
  TotalOrderPrice();
}
function TotalOrderPrice() {
  let totalOrderPrice = 0;
  purchaseOrderMaterials.value.forEach(item => {
    const selectedMaterial = materialsList.value.find(option => option.id === item.materialId);
    if (selectedMaterial) {
      item.totalPrice = selectedMaterial.price * item.purchaseOrderNumber;
    } else {
      item.totalPrice = 0;
    }
    totalOrderPrice += item.totalPrice;
  });
  form.value.orderPrice = totalOrderPrice;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    // console.log(response.data)
    purchaseOrderMaterials.value = response.data.purchaseOrderMaterials
    data.isAdding = false;
    open.value = true;
    title.value = "修改采购订单";
  });
}
const isApprove = (row) => {
  // 获取登录用户详细信息
  const loginUser = useUserStore().id;
  // 判断登录用户是否为审批人
  return row.eorderUserId === loginUser;
};
const isPurchaser = (row) => {
  // 获取登录用户详细信息
  const loginUser = useUserStore().id;
  // 判断登录用户是否为采购员
  return row.orderUserId === loginUser;
};
/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
function handleDeleteMaterial(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购申请编号为"' + _ids + '"的数据项？').then(function () {
    return delMaterial(_ids);
  }).then(() => {
    getList();
    form.value.purchaseOrderMaterials = purchaseOrderMaterials;
    proxy.$modal.msgSuccess("删除成功");
    TotalOrderPrice();
    getOrder(form.value.id).then(response => {
      form.value = response.data;
      purchaseOrderMaterials.value = response.data.purchaseOrderMaterials;
      TotalOrderPrice();
    });
  }).catch(() => {
  });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchase/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}
// 提交按钮操作函数
function handleSubmit(row) {
  ElMessageBox.confirm('是否确认提交？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 提交后状态变为 1
    row.status=1
    changeOrderStatus(row.id,row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 申请通过按钮操作函数
function handleApprove(row) {
  console.log('row: ', row);
  ElMessageBox.confirm('是否确认申请通过？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 申请通过后状态变为 2
    row.status=2
    changeOrderStatus(row.id, row.status).then(() => {
      getList();
      // 获取与该订单相关的申请ID
      // console.log(row.purchaseApplyId)
      changeStatus(row.purchaseApplyId, 4).then(() => {
      }).catch((error) => {
      });
    });
    //向应付表添加对应数据
    addPayable({purchaseOrderNo:row.purchaseOrderNo,amount:row.orderPrice}).then(resp => {
    })
  }).catch(() => {});
}

// 审核驳回按钮操作函数
function handleReject(row) {
  ElMessageBox.confirm('是否确认审核驳回？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 审核驳回后状态变为 3
    row.status = 3
    changeOrderStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 显示详情页
function handleShowDetails(row) {
  form.value = {...row };
  // 将采购申请列表数据赋值给详情页的列表数据
  purchaseOrderMaterials.value = row.purchaseOrderMaterials || [];
  openA.value = true;
  title.value = "采购订单详情";
  // 计算总价并赋值给每一项的总价字段
  // purchaseOrderMaterials.value.forEach(item => {
  //   item.totalPrice = item.materialPrice * item.purchaseOrderNumber;
  // });
  let totalOrderPrice = 0;
  purchaseOrderMaterials.value.forEach(item => {
    item.totalPrice = item.materialPrice * item.purchaseOrderNumber;
    totalOrderPrice += item.totalPrice;
  });
  form.value.orderPrice = totalOrderPrice;
}

getList();
</script>
